/* eslint-disable */
const Utils = {
  queryToJson (str, encode) {
    if (!str) {
      return {};
    }
    var param = str.split('&'),
      obj = {};
    for (var i = 0, len = param.length; i < len; i++) {
      var item = param[i].split('=');
      if (item[0]) {
        obj[item[0]] = item[1]
          ? encode ? decodeURIComponent(item[1]) : item[1]
          : '';
      }
    }
    return obj;
  },

  jsonToQuery (obj, encode) {
    var rs = [];
    if (obj) {
      for (var i in obj) {
        rs.push(i + '=' + (encode ? encodeURIComponent(obj[i]) : obj[i]));
      }
    }
    return rs.join('&');
  },

  version () {
     /*
      * navigator对象的属性
      * 浏览器代号: navigator.appCodeName
      * 浏览器名称: navigator.appName
      * 浏览器版本: navigator.appVersion
      * 启用Cookies: navigator.cookieEnabled
      * 硬件平台: navigator.platform
      * 用户代理: navigator.userAgent
      * 用户代理语言: navigator.systemLanguage
      */
      var u = window.navigator.userAgent, app = navigator.appVersion;
      var ua = u.toLowerCase();
      return {
        //移动终端浏览器版本信息
        trident: u.indexOf('Trident') > -1, //IE内核
        presto: u.indexOf('Presto') > -1, //opera内核
        webKit: u.indexOf('AppleWebKit') > -1, //苹果、谷歌内核
        gecko: u.indexOf('Gecko') > -1 && u.indexOf('KHTML') == -1, //火狐内核
        // mobile: !!u.match(/AppleWebKit.*Mobile.*/) || !!u.match(/AppleWebKit/), //是否为移动终端
        mobile: !!u.match(/Android/i) ||
                !!u.match(/webOS/i) ||
                !!u.match(/iPhone/i) ||
                !!u.match(/iPad/i) ||
                !!u.match(/iPod/i) ||
                !!u.match(/BlackBerry/i) ||
                !!u.match(/Windows Phone/i), //是否为移动终端
        ios: !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/), //ios终端
        android: u.indexOf('Android') > -1 || u.indexOf('Linux') > -1, //android终端或者uc浏览器
        iPhone: u.indexOf('iPhone') > -1 || u.indexOf('Mac') > -1, //是否为iPhone或者QQHD浏览器
        iPad: u.indexOf('iPad') > -1, //是否iPad
        iPod: u.indexOf('iPod') > -1, //是否iPad
        webApp: u.indexOf('Safari') == -1, //是否web应该程序，没有头部与底部
        isWeichat: ua.match(/MicroMessenger/i) == 'micromessenger'
      };
  },

  /**
   * @param (Object) ituns
   * @param (Object) iodAgreeMent
   * @param (Object) androidAgreeMent
   * @param (Object) appMarket
   *
   */
  openApp (opt) {
    var timer = null;
    if (this.version.iPhone || this.version.iPad || this.version.isPod) {
      var loadDateTime = new Date();
      clearTimeout(timer);
      timer = setTimeout(function () {
          var timeOutDateTime = new Date();
          if (timeOutDateTime - loadDateTime < 2000) {
            if (opt.ituns != undefined) {
              window.location.href = opt.ituns;
            }
          }
      }, 1000);
      if (opt.iosAgreeMent != undefined) {
        window.location.href = opt.iosAgreeMent;
      }
    } else {
      var loadDateTime = new Date();
      clearTimeout(timer);
      timer = setTimeout(function () {
        var timeOutDateTime = new Date();
        if (timeOutDateTime - loadDateTime < 2000) {
          if (opt.appMarket != undefined) {
            window.location.href = opt.appMarket;
          }
        }
      }, 1000);
      if (opt.androidAgreeMent != undefined) {
        window.location.href = opt.androidAgreeMent;
      }
    }
  },

  joinUrl (url, param, noHash) {
    if (!url) {
      url = window.location.href;
    }
    if (!param) {
      return url;
    }
    var Url = this.parseURL(url);

    var args = [];
    for (var i in param) {
      if (!i) {
        continue;
      }
      args.push(i + '=' + encodeURIComponent(param[i]));
    }
    var query = Url.query ? Url.query + '&' + args.join('&') : args.join('&');
    if (query) {
      query = '?' + query;
    }
    var path = Url.path;
    if (path) {
      path = '/' + path;
    }
    var hash = noHash ? '' : Url.hash ? '#' + Url.hash : '';
    return Url.origin + path + query + hash;
  },

  parseURL (a) {
    if (!a) {
      return null;
    }
    var b = /^((?:([A-Za-z]+):(\/{0,3}))?([0-9.\-A-Za-z]+\.[0-9A-Za-z]+)?(?::(\d+))?)(?:\/([^?#]*))?(?:\?([^#]*))?(?:#(.*))?$/,
      c = [
        'url',
        'origin',
        'scheme',
        'slash',
        'host',
        'port',
        'path',
        'query',
        'hash'
      ],
      d = b.exec(a),
      e = {};
    if (d) for (var f = 0, g = c.length; f < g; f += 1) e[c[f]] = d[f] || '';
    return e;
  },

  getURL (url) {
    url = url || window.location.href;
    // 去掉hash
    return url.replace(/#.*/, '');
  },

  buildDate (date) {
    if (typeof date == 'string') {
      date = date.replace(/-/g, '/');
      if (date.indexOf('/') >= 0) {
        date = new Date(date);
      } else {
        if (!isNaN(parseInt(date))) {
          date = new Date(parseInt(date));
        }
      }
    } else if (typeof date == 'number') {
      // 给的是秒
      if ((date + '').length <= 10) {
        date = date * 1000;
      }
      date = new Date(date);
    } else if (!(date instanceof Date)) {
      return false;
    }
    return date;
  },

  formatDate (dd, fmt) {
    var date = this.buildDate(dd);
    if (!date) {
      return dd;
    }
    var o = {
      'M+': date.getMonth() + 1, //月份
      'd+': date.getDate(), //日
      'h+': date.getHours(), //小时
      'm+': date.getMinutes(), //分
      's+': date.getSeconds(), //秒
      'q+': Math.floor((date.getMonth() + 3) / 3), //季度
      S: date.getMilliseconds() //毫秒
    };
    if (/(y+)/.test(fmt)) {
      fmt = fmt.replace(
        RegExp.$1,
        (date.getFullYear() + '').substr(4 - RegExp.$1.length)
      );
    }

    for (var k in o) {
      if (new RegExp('(' + k + ')').test(fmt)) {
        fmt = fmt.replace(
          RegExp.$1,
          RegExp.$1.length == 1
            ? o[k]
            : ('00' + o[k]).substr(('' + o[k]).length)
        );
      }
    }
    return fmt;
  },

  trim (str) {
    return str.replace(/^\s+|\s+$/, '')
  },

  getLimitString (str, length, suffix) {
    if (!str) {
      return str;
    }
    if (this.bLength(str) < length) {
      return str;
    }
    if (typeof suffix === 'undefined') {
      suffix = suffix || '..';
    }

    length = length - suffix.length;

    var totalLength = str.length,
      count;
    var realLength = 0;
    for (var i = 0; i < totalLength; i++) {
      var code = str.charCodeAt(i);
      if (code >= 0 && code <= 128) {
        realLength += 1;
      } else {
        realLength += 2;
      }
      if (realLength >= length) {
        break;
      }
    }

    return str.substring(0, i) + suffix;
  },

  bLength (str) {
    if (str == null) return 0;
    if (typeof str != 'string') {
      str += '';
    }
    var totalLength = str.length;
    var realLength = 0;
    for (var i = 0; i < totalLength; i++) {
      var code = str.charCodeAt(i);
      if (code >= 0 && code <= 128) {
        realLength += 1;
      } else {
        realLength += 2;
      }
    }
    return realLength;
  },

  betweenTime (myTime, serverTime) {
    var before = this.buildDate(myTime),
      serverTime = this.buildDate(serverTime);
    if (!serverTime || !before) {
      return '';
    }
    var distance = serverTime.getTime() - before.getTime();

    function getPosNumber(number) {
      if (number % 1 == 0) {
        return number;
      }
      return Math.floor(number) + 1;
    }
    if (distance < 0) {
      return '将来';
    }
    distance = distance / 1000;
    if (distance < 60) {
      return '刚刚';
    }
    // 小于 一个小时，提示分钟
    if (distance < 3600) {
      return getPosNumber(distance / 60) + '分钟之前';
    }
    // 小于24小时，提示小时
    if (distance < 86400) {
      return getPosNumber(distance / 3600) + '小时之前';
    }
    // 小于一个月，显示天
    if (distance < 2592000) {
      return getPosNumber(distance / 86400) + '天前';
    }
    //大于一天，显示时间显示几天前
    return;
    this.formatDate(before, 'yyyy-MM-dd');
  },

  getImgPathBySize (path,width,height) {
    if (!path) {
      return path;
    }
    width = width || 400;
    //height = typeof height == "undefined"? 300 : '';
    height = (typeof height != "undefined" && height)? height : '';
    var suffixIndex = path.lastIndexOf(".");
    var suffix = path.substring(suffixIndex);
    var center = "."+width+"x"+height;
    if (path.indexOf(center) >=0) {
      return path;
    }
    return path +center+suffix;
  },
  /**
   * 写入cookie
   * @param key
   * @param value
   * @param attributes
   * @returns {string}
   */
  cookie: {
    set(key, value, options) {
      let days, time, result, decode, cookieValue
      let regPatt = new RegExp('(?:^|; )' + encodeURIComponent(key) + '=([^;]*)', 'g')

      // A key and value were given. Set cookie.
      if (arguments.length > 1 && String(value) !== '[object Object]') {
        // Enforce object
        options = Object.assign({}, options)

        if (value === null || value === undefined) options.expires = -1

        if (typeof options.expires === 'number') {
          days = (options.expires * 24 * 60 * 60 * 1000)
          time = options.expires = new Date()

          time.setTime(time.getTime() + days)
        }

        value = String(value)

        return (document.cookie = [
          encodeURIComponent(key), '=',
          // options.raw ? value : encodeURIComponent(value),
          options.encode ? (options.encode === 'uri' ? encodeURIComponent(value) : escape(value)) : value,
          options.expires ? '; expires=' + options.expires.toUTCString() : '',
          options.path ? '; path=' + options.path : '',
          options.domain ? '; domain=' + options.domain : '',
          options.secure ? '; secure' : ''
        ].join(''))
      }
      // Key and possibly options given, get cookie
      options = value || {}

      // decode = options.raw ? function (s) { return s } : decodeURIComponent
      // decode = options.raw ? function (s) { return s } : unescape
      decode = options.encode ? (options.encode === 'uri' ? decodeURIComponent : unescape) : function(s) { return s }

      // return (result = new RegExp('(?:^|; )' + encodeURIComponent(key) + '=([^;]*)').exec(document.cookie)) ? decode(result[1]) : null
      while ((result = regPatt.exec(document.cookie)) != null) {
        cookieValue = result[1]
      }
      return cookieValue ? decode(cookieValue) : null
    },

    /**
     * 获取cookie
     * @param key
     * @param jsJson
     * @returns {*}
     */
    get(key, jsJson) {
      var result
      if (!key) {
        result = {}
      }

      // To prevent the for loop in the first place assign an empty array
      // in case there are no cookies at all. Also prevents odd result when
      // calling "get()"
      var cookies = document.cookie ? document.cookie.split('; ') : []
      var rdecode = /(%[0-9A-Z]{2})+/g
      var i = 0

      for (; i < cookies.length; i++) {
        var parts = cookies[i].split('=')
        var cookie = parts.slice(1).join('=')

        if (cookie.charAt(0) === '"') {
          cookie = cookie.slice(1, -1)
        }

        try {
          var name = parts[0].replace(rdecode, decodeURIComponent)
          cookie = cookie.replace(rdecode, decodeURIComponent)

          if (jsJson) {
            try {
              cookie = JSON.parse(cookie)
            } catch (e) {}
          }

          if (key === name) {
            result = cookie
            break
          }

          if (!key) {
            result[name] = cookie
          }
        } catch (e) {}
      }

      return result
    },

    /**
     * 移除cookie
     * @param key
     * @param attributes
     */
    remove(name, options) {
      // this.set(name, null, {
      //   path: '/',
      //   domain: window.location.hostname.substring(window.location.host.indexOf('.'))
      // })
      // this.set(name, null, {
      //   path: '/'
      // })
      let params = Object.assign({
        expires: -1
      }, options)

      this.set(name, null, params)
    }
  },
  /**
   * 异步加载js
   * Options:
   *  - timeout {Number} how long after a timeout error is emitted (`60000`)
   *
   * @param {String} url
   * @param {Object} optional options
   * @param {Function} optional callback
   * @return {Promise}
   */
  loadJs ({url, options = {}, cb}) {
    return new Promise((resolve, reject) => {
      if (!url) {
        reject(new Error('NO URL'))
      }

      let timeout = options.timeout || 60000
      let target = document.getElementsByTagName('body')[0] || document.body
      let timer, script

      // 超时自动取消
      if (timeout) {
        timer = setTimeout(() => {
          cleanup()
          reject(new Error('Timeout'))
        }, timeout)
      }

      // 清理函数
      function cleanup () {
        if (script.parentNode) {
          script.parentNode.removeChild(script)
        }
        if (timer) {
          clearTimeout(timer)
        }
      }

      // 创建js文件
      script = document.createElement('script')
      script.type = 'text/javascript'
      script.charset = 'utf-8'
      script.async = true
      script.src = url
      target.appendChild(script)

      //  IE的script 元素支持onreadystatechange事件，不支持onload事件  FF的script
      // 元素不支持onreadystatechange事件，只支持onload事件
      script.onload = script.onreadystatechange = function () {
        if (!script.readyState || script.readyState === 'loaded' || script.readyState === 'complete') {
          resolve()
          if (timer) {
            clearTimeout(timer)
          }
        }
      }
    }).then(() => {
      cb && cb()
    })

  },
  /**
   *
   *
   */

  /*
  * @function 动态加载css文件
  * @param {string} options.url -- css资源路径
  * @param {function} options.callback -- 加载后回调函数
  * @param {string} options.id -- link标签id
  */
  loadCss (options) {
    var url = options.url,
        callback = typeof options.callback == "function" ? options.callback : function(){},
        id = options.id,
        node = document.createElement("link"),
        supportOnload = "onload" in node,
        isOldWebKit = +navigator.userAgent.replace(/.*(?:AppleWebKit|AndroidWebKit)\/?(\d+).*/i, "$1") < 536, // webkit旧内核做特殊处理
        protectNum = 300000 // 阈值10分钟，一秒钟执行pollCss 500次

    node.rel = "stylesheet"
    node.type = "text/css"
    node.href = url
    if( typeof id !== "undefined" ){
        node.id = id
    }
    document.getElementsByTagName("head")[0].appendChild(node)

    // for Old WebKit and Old Firefox
    if (isOldWebKit || !supportOnload) {
      // Begin after node insertion
      setTimeout(function() {
          pollCss(node, callback, 0)
      }, 1)
      return
    }

    if(supportOnload){
      node.onload = onload
      node.onerror = function() {
        // 加载失败(404)
        onload()
      }
    }else{
      node.onreadystatechange = function() {
        if (/loaded|complete/.test(node.readyState)) {
          onload()
        }
      }
    }

    function onload() {
      // 确保只跑一次下载操作
      node.onload = node.onerror = node.onreadystatechange = null

      // 清空node引用，在低版本IE，不清除会造成内存泄露
      node = null

      callback()
    }

    // 循环判断css是否已加载成功
    /*
    * @param node -- link节点
    * @param callback -- 回调函数
    * @param step -- 计步器，避免无限循环
    */
    function pollCss(node, callback, step){
      var sheet = node.sheet,
          isLoaded

      step += 1

      // 保护，大于10分钟，则不再轮询
      if(step > protectNum){
          isLoaded = true

          // 清空node引用
          node = null

          callback()
          return
      }

      if(isOldWebKit){
        // for WebKit < 536
        if(sheet){
          isLoaded = true
        }
      }else if(sheet){
        // for Firefox < 9.0
        try{
          if(sheet.cssRules){
            isLoaded = true
          }
        }catch(ex){
          // 火狐特殊版本，通过特定值获知是否下载成功
          // The value of `ex.name` is changed from "NS_ERROR_DOM_SECURITY_ERR"
          // to "SecurityError" since Firefox 13.0. But Firefox is less than 9.0
          // in here, So it is ok to just rely on "NS_ERROR_DOM_SECURITY_ERR"
          if(ex.name === "NS_ERROR_DOM_SECURITY_ERR"){
            isLoaded = true
          }
        }
      }

      setTimeout(() => {
        if(isLoaded){
          // 延迟20ms是为了给下载的样式留够渲染的时间
          callback()
        }else{
          pollCss(node, callback, step)
        }
      }, 20)
    }
  },
  _throttle (fn, time) {
    let _self = fn,
        timer,
        firstTime = true
    return function () {
      let args = arguments, //解决闭包传参问题
          _me = this //解决上下文丢失问题
      if(firstTime) { //若是第一次，则直接执行
        _self.apply(_me, args)
        return firstTime = false
      }
      if(timer) { //定时器存在，说明有事件监听器在执行，直接返回
        return false
      }

      timer = setTimeout(function() {
        clearTimeout(timer)
        timer = null
        _self.apply(_me, args)
      }, time || 500)
    }
  }
}
Utils.install = function (Vue, options) {
  Vue.prototype.$utils = Utils
}
export default Utils
